import type { TableColumnCtx } from 'element-plus'
import { getConsumptionUnitStatistics } from '@/api/modules/consumption'
import type { STORAGE_MODES } from '@/enum/modules/indicator'

function getData() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        thead: [
          { label: '日期', prop: 'date', width: '200px' },
          { label: '电力（千瓦时）', prop: 'electric' },
          { label: '原水（立方米）', prop: 'water' },
          { label: '天然气（立方米）', prop: 'gas' },
          { label: '煤炭（吨）', prop: 'coal' },
          { label: '综合能耗（吨标准煤）', prop: 'consumption' },
        ],
        tbody: [
          { date: '2021-01-01', electric: 100, water: 100, gas: 100, coal: 100, consumption: 100 },
          { date: '2021-01-02', electric: 100, water: 100, gas: 100, coal: 100, consumption: 100 },
          { date: '2021-01-03', electric: 100, water: 100, gas: 100, coal: 100, consumption: 100 },
        ],
      })
    }, 300)
  })
}

export enum REPORT_TYPES {
  DATE = 1,
  MONTH = 2,
  YEAR = 3,
}

export type ColumnType = {
  label: string
  prop: string
} & Partial<Omit<TableColumnCtx<any>, 'label' | 'prop'>>
export function useEnergyConsumingUnit() {
  const [loading, setLoading] = useState(false)
  const [columns, setColumns] = useShallowState<ColumnType[]>([])
  const [tableData, setTableData] = useState<any[]>([])

  async function getEnergyConsumingUnitData(
    params: {
      pointId: number
      timeType: STORAGE_MODES
      time: string
    },
  ) {
    setLoading(true)
    try {
      const { data } = await getConsumptionUnitStatistics(params)
      setColumns(data.thead || [])

      const t = (data.tbody || [])[0]
      const iterate = (key: string): number => {
        return data.tbody.reduce((pre: number, cur: any) => {
          return pre + (Number(cur[key]) || 0)
        }, 0)
      }
      if (t) {
        // 合计
        const summary = Object.keys(t).reduce((acc: any, key) => {
          if (key === 'time') {
            acc[key] = '合计'
          }
          else {
            acc[key] = +(iterate(key).toFixed(2)) || 0
          }
          return acc
        }, {})
        data.tbody.push(summary)
      }

      setTableData(data.tbody || [])
    }
    catch (e) {
      console.warn(e)
    }
    finally {
      setLoading(false)
    }
  }

  return {
    loading,
    columns,
    tableData,
    getEnergyConsumingUnitData,
  }
}
